package mall

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 商城列表
func NewMallListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallListLogic {
	return &MallListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallListLogic) MallList(req *types.MallListRequest) (resp *types.MallListResponse, err error) {
	mallDao := mall.NewMallDao(l.ctx, l.svcCtx)

	// 查询商城
	malls, total, err := mallDao.MallConditionsPageAll(req.Current, req.PageSize, nil)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询商城图标列表失败%v", err))
	}

	//组装返回数据
	list := lo.Map(malls, func(item *ent.HzMall, _ int) *types.MallList {
		createdAt := ""
		if item.CreatedAt != 0 {
			createdAt = time.Unix(item.CreatedAt, 0).Format(time.DateTime)
		}
		return &types.MallList{
			Id:        int64(item.ID),
			CreatedAt: createdAt,
			Sort:      item.MallSort,
			MallIcon:  constant.MallGoodsImage + item.MallIcon,
			MallName:  item.MallName,
			MallUrl:   item.MallURL,
			Status:    item.MallStatus,
		}
	})

	//组装返回数据
	resp = &types.MallListResponse{
		Page: &types.PageResponse{
			Total:           total,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: list,
	}

	return resp, nil
}
